<template>
  <a-modal :title="title" :visible="visible" :footer="null" width="60%" keyboard @cancel="handleCancel">
    <a-button v-permission="{ meta: $route.meta, permissionCode: 'FUNS_ADD' }" class="table-operations" @click="onAdd" type="primary">新建</a-button>
    <a-table :columns="columns" :dataSource="data" :rowKey="(record) => record.id" :pagination="false" bordered>
      <!-- prettier-ignore -->
      <template v-for="col in ['name', 'permissionCode', 'url', 'seq']" v-slot:[col]='text, record'>
      <div :key="col">
        <a-input v-if="record.editable && col!=='seq'" style="margin: -5px 0" :value="record[col]" v-model="editingData[col]"  />
        <a-input-number v-else-if="record.editable && col==='seq'" style="margin: -5px 0" :value="record[col]" v-model="editingData[col]" />
        <template v-else>{{ text }}</template>
      </div>
    </template>
      <template v-slot:operation="record">
        <div class="table-row-operations">
          <span v-if="record.editable">
            <a @click="() => save()">保存</a>
            <a-popconfirm title="确定要取消吗?" @confirm="() => cancel()">
              <a>取消</a>
            </a-popconfirm>
          </span>
          <span v-else>
            <a v-permission="{ meta: $route.meta, permissionCode: 'FUNS_UPDATE' }" :disabled="editingData.id" @click="() => onEdit(record)">编辑</a>
            <a-popconfirm v-permission="{ meta: $route.meta, permissionCode: 'FUNS_DELETE' }" title="Sure to delete?" @confirm="() => onDelete(record)">
              <a href="javascript:;">删除</a>
            </a-popconfirm>
          </span>
        </div>
      </template>
    </a-table>
  </a-modal>
</template>
<script>
const columns = [
  {
    title: '名称',
    dataIndex: 'name',
    scopedSlots: { customRender: 'name' }
  },
  {
    title: '权限标记',
    dataIndex: 'permissionCode',
    scopedSlots: { customRender: 'permissionCode' }
  },
  {
    title: 'API地址',
    dataIndex: 'url',
    scopedSlots: { customRender: 'url' }
  },
  {
    title: '排序',
    dataIndex: 'seq',
    scopedSlots: { customRender: 'seq' }
  },
  {
    title: 'operation',
    key: 'operation',
    scopedSlots: { customRender: 'operation' }
  }
]
import permission from '@/directive/permission' // 权限判断指令
import { saveCascade, delCascade } from '@/api/fun'

const defaultEditingData = {
  id: undefined,
  name: '',
  url: '',
  seq: undefined,
  permissionCode: '',
  permId: undefined
}

export default {
  directives: { permission },
  data() {
    return {
      title: '',
      visible: false,
      moduleId: undefined,
      data: [],
      columns,
      editingData: defaultEditingData
    }
  },
  watch: {
    editingData({ id }) {
      const newData = [...this.data]
      if (id) {
        const target = newData.find((item) => id === item.id)
        if (target) {
          this.editingData = target
          target.editable = true
          this.data = newData
        }
      } else {
        const target = newData.find((item) => item.editable)
        if (target) {
          delete target.editable
        }
        this.data = newData
      }
    }
  },
  methods: {
    handleCancel(e) {
      this.visible = false
      this.editingData = { ...defaultEditingData }
    },
    onAdd() {
      // init editData
      const _editingData = { ...defaultEditingData }
      _editingData.id = -1
      _editingData.moduleId = this.moduleId
      // change this dada
      this.data = [...this.data, _editingData]
      this.editingData = _editingData
    },
    onEdit(record) {
      this.editingData = record
    },
    async onDelete(record) {
      const key = 'delFun'
      try {
        this.$message.loading({ content: '正在删除...', key })
        let res = await delCascade(record.id)
        this.$message.success({ content: '删除成功!', key, duration: 2 })
        // this.$emit('refreshTable')
        const newData = this.data.filter((e) => e.id !== record.id)
        this.data = [...newData]
        this.editingData = { ...defaultEditingData }
      } catch (err) {
        this.$message.error({ content: '删除失败!', key, duration: 2 })
        console.error(err.message)
      }
    },
    async save() {
      const _editingData = { ...this.editingData }
      // -1 表示 add
      if (_editingData.id > 0) {
        const res = await saveCascade(_editingData)
        this.$message.success({ content: '修改成功!', duration: 2 })
      } else {
        delete _editingData.id
        const res = await saveCascade(_editingData)
        _editingData.id = res.data.id
        _editingData.permId = res.data.permId
        this.$message.success({ content: '添加成功!', duration: 2 })
      }
      // this.$emit('refreshTable')
      const newData = this.data.map((e) => {
        // -1 表示 add
        if (e.id === -1 || e.id === _editingData.id) {
          e = { ..._editingData }
        }
        return e
      })
      this.data = [...newData]
      this.editingData = { ...defaultEditingData }
    },
    cancel() {
      const newData = this.data.filter((e) => e.id !== -1)
      this.data = [...newData]
      this.editingData = { ...defaultEditingData }
    }
  }
}
</script>
